<?php

namespace app\cps\service;

use app\model\LaunchAccount;
use think\facade\Db;
use app\common\Common;
use app\common\Error;
use think\facade\Cache;
use app\model\Company;
use app\model\Link;
use app\model\PayRecord;
use app\model\Videos;
use app\cps\service\LinkService;

class LaunchAccountService
{
    private $model;
    private $companyModel;
    private $linkModel;
    private $payRecordModel;
    private $videoModel;
    private $linkService;

    public function __construct(LaunchAccount $model, Company $companyModel, Link $linkModel, PayRecord $payRecordModel, Videos $videoModel, LinkService $linkService)
    {
        $this->model = $model;
        $this->companyModel = $companyModel;
        $this->linkModel = $linkModel;
        $this->payRecordModel = $payRecordModel;
        $this->videoModel = $videoModel;
        $this->linkService = $linkService;
    }

    // 投放账户列表
    public function getLaunchAccountList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where = [];
        if (!empty($params['company_id'])) {
            $where[] = ['company_id', '=', $params['company_id']];
        }

        if (!empty($params['account_id'])) {
            $where[] = ['account_id', '=', $params['account_id']];
        }

        if (!empty($params['platform'])) {
            $where[] = ['platform', '=', $params['platform']];
        }

        if (!empty($params['account_name'])) {
            $where[] = ['account_name', 'like', '%'.$params['account_name'].'%'];
        }

        $data = $this->model->getPagingDataByWhere($where, $page, $limit, 'id, company_id, account_id, platform, subject, rebate, status, created_at, account_name');
        if ($data['data']) {
            $companyIds = array_column($data['data'], 'company_id');
            $companyData = $this->companyModel->getDataByWhere(['id' => $companyIds], 'id, name');
            $company = array_column($companyData, 'name', 'id');
            foreach ($data['data'] as $key => $value) {
                $data['data'][$key]['company_name'] = $company[$value['company_id']];
            }
        }

        return $data;
    }

    // 获取投放账户详情
    public function getLaunchAccountDetail(int $id)
    {
        $data = $this->model->getInfoByWhere(['id' => $id], 'id, company_id, account_id, rebate, status, platform, subject, account_name');
        return $data;
    }

    // 添加/修改
    public function edit($params)
    {
        if (empty($params['id'])) {
            $params['created_at'] = time();
            $data = $this->model->getInfoByWhere(['account_id' => $params['account_id']], 'id');
            if ($data) {
                return ['message' => Error::THE_ACCOUNT_IS_EXISTS];
            }
        } else {
            $params['updated_at'] = time();
        }

        $redis = Cache::store('redis')->handler();
        $redis->select(5);

        $redisData = $advertiserData = [];

        if ($params['platform'] == 1) {
            $redisKey = config('redis_key.huge_amount_advertising_account_info');
        } else if ($params['platform'] == 2) {
            $redisKey = config('kwai.magnetic_force_advertising_account_info');
        } else if ($params['platform'] == 3) {
            $redisKey = config('baidu.baidu_sub_user_list');
            $advertiserData = $redis->hGetAll($redisKey);
        }
        $length = $redis->scard($redisKey);

        if ($length) {
            $result = $redis->smembers($redisKey);
            foreach ($result as $item) {
                $redisData[] = json_decode($item, true);
            }
            $advertiserData = array_column($redisData, 'advertiser_name', 'advertiser_id'); // advertiser_id,advertiser_name
        }

        $params['account_name'] = empty($advertiserData[$params['account_id']]) ? '' : $advertiserData[$params['account_id']];

        $bool = $this->model->edit($params);
        return $bool;
    }

    // 获取合作公司下拉列表
    public function getCompanySelectList()
    {
        $data = $this->companyModel->getDataByWhere();
        return $data;
    }

    // 获取订单列表
    public function getOrderList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $accountId = $params['account_id'];

        $linkData = $this->linkModel->getDataByWhere(['advertiser_id' => $accountId], 'id');
        $linkIds = array_column($linkData, 'id');
        $where[] = ['link_id', 'in', $linkIds];

        // 用户ID
        if (!empty($params['uid'])) {
            $where[] = ['uid', '=', $params['uid']];
        }
        // 支付状态
        if (isset($params['status']) && is_numeric($params['status'])) {
            $where[] = ['status', '=', $params['status']];
        }

        // 支付时间
        if (!empty($params['start_time'])) {
            $where[] = ['pay_time', '>=', strtotime($params['start_time'])];
        }
        if (!empty($params['end_time'])) {
            $where[] = ['pay_time', '<=', strtotime($params['end_time'] . ' 23:59:59')];
        }

        // 短剧
        if (!empty($params['video_id'])) {
            $where[] = ['video_id', '=', $params['video_id']];
        }

        $data = $this->payRecordModel->getPagingDataByWhere($where, $page, $limit, 'id, uid, video_id, order_no, type, total_fee, status, pay_time, link_id, advertiser_id');

        if ($data['data']) {
            $videoIds = array_column($data['data'], 'video_id');
            $videoData = $this->videoModel->getDataByIds($videoIds, 'id, name');
            $video = array_column($videoData, 'name', 'id');
            foreach ($data['data'] as $key => $value) {
                $data['data'][$key]['video_name'] = !empty($value['video_id']) ? $video[$value['video_id']] : '';
            }
        }

        return $data;
    }

    // 批量同步账户数据
    public function batchSyncAccount()
    {
        $this->linkService->getAccountSelectList(['is_refresh' => 1]);
        $this->linkService->getKwaiAccountSelectList(['is_refresh' => 1]);

        $redis = Cache::store('redis')->handler();
        $redis->select(5);

        $redisKey = config('redis_key.huge_amount_advertising_account_info');
        $length = $redis->scard($redisKey);
        $tiktokAdvertiserData = [];

        if ($length) {
            $result = $redis->smembers($redisKey);
            foreach ($result as $item) {
                $tiktokAdvertiserData[] = json_decode($item, true);
            }
        }

        $kuaiRedisKey = config('kwai.magnetic_force_advertising_account_info');
        $length = $redis->scard($kuaiRedisKey);
        $kuaiAdvertiserData = [];

        if ($length) {
            $result = $redis->smembers($kuaiRedisKey);
            foreach ($result as $item) {
                $kuaiAdvertiserData[] = json_decode($item, true);
            }
        }

        $sql = 'truncate table ly_launch_account';
        $query = Db::query($sql);

        $account = [];
        // 快手
        foreach ($kuaiAdvertiserData as $advertiserId => $value) {

            $advertiserName = $value['advertiser_name'];
            $rebate = 7;
            $subject = '比翼鸟';

            $account[] = [
                'company_id' => 3,
                'account_id' => $value['advertiser_id'],
                'account_name' => $advertiserName,
                'status' => 1,
                'rebate' => $rebate,
                'subject' => $subject,
                'platform' => 2,
                'created_at' => time()
            ];
        }
        // 抖音
        foreach ($tiktokAdvertiserData as $advertiserId => $value) {
            $advertiserName = $value['advertiser_name'];
            if (stristr($advertiserName, 'PR')) {
                $rebate = 6;
                $subject = '派瑞';
            } else if (stristr($advertiserName, 'ax')) {
                $rebate = 5;
                $subject = '傲星';
            } else if (stristr($advertiserName, '乐推')) {
                $rebate = 6;
                $subject = '乐推';
            } else {
                $rebate = 5;
                $subject = '比翼鸟';
            }

            $account[] = [
                'company_id' => 3,
                'account_id' => $value['advertiser_id'],
                'account_name' => $advertiserName,
                'status' => 1,
                'rebate' => $rebate,
                'subject' => $subject,
                'platform' => 1,
                'created_at' => time()
            ];
        }

        $bool = Db::name('launch_account')->insertAll($account);
        return $bool;
    }

    // 批量修改账户
    public function batchUpdateAccount($params)
    {
        $platform = $params['platform'];

        $where = [
            ['platform', '=', $platform],
            ['account_name', 'like', '%'.$params['subject'].'%']
        ];
        $accountData = $this->model->getDataByWhere($where, 'id, account_id, account_name');

        $saveData = [];
        foreach ($accountData as $item) {
            if (stristr($item['account_name'], $params['subject'])) {
                $saveData[] = ['id' => $item['id'], 'rebate' => $params['rebate']];
            }
        }

        $bool = $this->model->saveAll($saveData);
        return $bool;
    }
}